package com.ai.web;

import com.ai.common.http.SubscriberImpl;
import com.ai.common.http.TransferStationClient;
import com.ai.sevice.abc.ZuoweninfoDataParagraph;
import com.ai.sevice.abc.ZuowenpaperDataListRecommend;
import com.ai.sevice.ai.remote.CompletionsRequest;
import com.ai.sevice.ai.remote.Message;
import com.ai.sevice.AbcService;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import reactor.core.publisher.Flux;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 测试Controller
 * @author ：shengwenyang
 * @date ：Created in 2023/4/12 16:48
 * @description：
 * @version:
 */
@Slf4j
@RestController
@RequestMapping(value = "abc")
@CrossOrigin(origins = "*",maxAge = 3600)
public class AbcController {

    @Autowired
    private AbcService abcService;
    @Autowired
    private TransferStationClient transferStationClient;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 获取缓存
     * @return
     */
    @GetMapping(value = "getCache1")
    public List<ZuoweninfoDataParagraph> getCache1() {
        ZuoweninfoDataParagraph request = new ZuoweninfoDataParagraph();
        request.setContentType("x");
        request.setText("tex");
        return abcService.getCache1(request,"aa",123,true);
    }

    /**
     * 获取缓存
     * @return
     */
    @GetMapping(value = "getCache2")
    public List<ZuowenpaperDataListRecommend> getCache2() {
        return abcService.getCache2("abc");
    }

    /**
     * 获取程序代码答案
     * @return
     */
    @GetMapping(value = "getProgrammerAnswer")
    public String getProgrammerAnswer() {
        abcService.getProgrammerAnswer();
        return "ok";
    }

    /**
     * 获取满分作文
     * @return
     */
    @GetMapping(value = "getFullScore")
    public String getFullScore() {
        abcService.getFullScore();
        return "ok";
    }

    /**
     * 服务压测
     * @return
     */
    @GetMapping(value = "stressTesting")
    public String stressTesting() {
        abcService.stressTesting();
        return "ok";
    }

    /**
     * 股票测试
     * @return
     */
    @GetMapping(value = "stock1")
    public String stock1() {
        abcService.stock1();
        return "ok";
    }

    /**
     * 股票测试
     * @return
     */
    @GetMapping(value = "stock2")
    public String stock2() {
        abcService.stock2();
        return "ok";
    }

    @GetMapping(value = "setRedis")
    public String setRedis(String key, String value) {
//        RMap<String, String> map = redissonClient.getMap("myMap");
//        map.put(key, value);
        RBucket<Object> myBucket = redissonClient.getBucket("myBucket");
        myBucket.set("ysw",5, TimeUnit.SECONDS);
        return "ok";
    }

    @GetMapping(value = "getRedis")
    public Object getRedis(String key) {
//        RMap<String, String> map = redissonClient.getMap("myMap");
//        return map.get(key);
        RBucket<Object> myBucket = redissonClient.getBucket(key);
        return myBucket.get();
    }

    @PostMapping(value = "deleteRedis")
    public String deleteRedis(@RequestBody Map<String,String> request) {
        String bucket = request.get("bucket");
        RBucket<String> myBucket = redissonClient.getBucket(bucket);
        myBucket.delete();
        return "ok";
    }

    /**
     * 流式返回
     * @return
     */
    @GetMapping(value = "completionsFlux",produces = "text/event-stream;charset=UTF-8")
    public Flux<String> completionsFlux(){
        String token = "Bearer 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";
        CompletionsRequest request = new CompletionsRequest();
        request.setModel("gpt-3.5-turbo");
        request.setMax_tokens(new BigDecimal("4000"));
        request.setTemperature(new BigDecimal("0.5"));
        request.setFrequency_penalty(new BigDecimal("0"));
        request.setPresence_penalty(new BigDecimal("0"));
        request.setMessages(Arrays.asList(new Message("user","用java写一个冒泡排序")));
        return transferStationClient.completionsFlux(request,token);
    }

    /**
     * 流式返回，改变参数
     * @return
     */
    @GetMapping(value = "completionsFlux2",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> completionsFlux2(){
        String token = "Bearer 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";
        CompletionsRequest request = new CompletionsRequest();
        request.setModel("gpt-3.5-turbo");
        request.setMax_tokens(new BigDecimal("4000"));
        request.setTemperature(new BigDecimal("0.5"));
        request.setFrequency_penalty(new BigDecimal("0"));
        request.setPresence_penalty(new BigDecimal("0"));
        request.setMessages(Arrays.asList(new Message("user","用java写一个冒泡排序")));

        return Flux.create(emitter -> {
            SubscriberImpl subscriber = new SubscriberImpl(emitter);
            Flux<String> openAiResponse = transferStationClient.completionsFlux(request,token);
            openAiResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }

    /**
     * 获取服务器时间
     * @return
     */
    @GetMapping(value = "getTime")
    public String getDateTime(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 异步处理
     * @return
     */
    @GetMapping(value = "async")
    public String async(){
        abcService.async();
        return "成功";
    }

    /**
     * https://blog.csdn.net/tonysong111073/article/details/127144426
     * https://qa.1r1g.com/sf/ask/3389511821/
     * @return
     */
    @GetMapping(value = "flux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> flux(){
        Flux<String> just = Flux.just("WebFlux", "是从", "Spring Framework5.0", "以后开始引入的响应式web编程框架。");
        return just;
    }

    /**
     * 返回到页面
     * @return
     */
    @GetMapping(value = "ai")
    public ModelAndView aiHome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("ai");
        return modelAndView;
    }

    /**
     * 返回到页面
     * @return
     */
    @GetMapping(value = "index")
    public ModelAndView indexHome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * 返回到页面
     * @return
     */
    @GetMapping(value = "upload")
    public ModelAndView uploadHome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("upload"); //视图的名称为upload.html
        return modelAndView;
    }

    /**
     * 文件上传
     * @param file
     * @param path
     * @return
     * @throws Exception
     */
    @PostMapping(value = "upload")
    public String upload(@RequestParam MultipartFile file,@RequestParam(required = false) String path,@RequestParam(required = false) String password) throws Exception {
        return abcService.upload(file,path,password);
    }

    /**
     * 文件下载
     * @param name
     * @param path
     * @return
     * @throws IOException
     */
    @GetMapping("download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String name, @RequestParam(required = false) String path) throws IOException {

        String filePath = "/usr/local/metal/";
        if (StringUtils.isNotBlank(path)){
            filePath = path;
        }
        File file = new File(filePath + name);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
        headers.add(HttpHeaders.CONTENT_TYPE, Files.probeContentType(file.toPath()));

        Resource resource = new FileSystemResource(file);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);
    }

    @PostMapping("uploadImage")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成新的文件名
        String newFileName = UUID.randomUUID().toString() + suffixName;
        // 保存文件
        File dest = new File("D:/资料/icon/" + newFileName);
        file.transferTo(dest);
        // 压缩图片
        //Thumbnails.of(dest).scale(0.5f).toFile(dest);
        //裁剪
        BufferedImage inputImage = ImageIO.read(dest);
        Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(inputImage)
                .size(1000, 1000)
                .outputQuality(0.8);
        //将压缩后的图像保存到文件或输出流中
        builder.toFile(dest);
        // 返回文件名
        return newFileName;
    }

}
